/**
 *
 */
package cn.dw.mm.service.impl;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.dw.mm.service.InspectionsceneService;
import cn.dw.mm.controller.FileUploadController;
import cn.dw.mm.domain.Inspectionproblem;
import cn.dw.mm.domain.Inspectionscene;
import cn.dw.mm.mapper.InspectionsceneMapper;

@Service
public class InspectionsceneServiceImpl implements InspectionsceneService {
	
	@Autowired
	private InspectionsceneMapper inspectionsceneMapper;
	
	@Override
	public List<Inspectionproblem> selectByProblemId(Integer problemId) {
		return inspectionsceneMapper.selectByProblemId(problemId);
	}
	
	@Override
	public List<Inspectionproblem> selectByCondition(Inspectionproblem inspectionscene) {
		return inspectionsceneMapper.selectByCondition(inspectionscene);
	}
	
	@Override
	public int delete(Inspectionscene inspectionscene) {
		int deleteFlag = inspectionsceneMapper.deleteById(inspectionscene.getId());
		//确定删除工单成功后再进行支撑材料删除操作
		if (deleteFlag == 1) {
			//只要工单删除成功，支撑材料删没删成功都直接返回1
			FileUploadController fUp = new FileUploadController();
			fUp.deleteXcxcFile(inspectionscene.getSupMaterial());
			return 1;
		} else {
			return -1;
		}
	}
	
	@Override
	public int insert(HttpServletRequest request) {
		
		Inspectionscene inspectionscene = new Inspectionscene();//通过request构造实体类
		inspectionscene.setProDescription(request.getParameter("proDescription"));
		inspectionscene.setApplicableLaws(request.getParameter("applicableLaws"));
		inspectionscene.setInspectedUnit(request.getParameter("inspectedUnit"));
		inspectionscene.setCenManagement(request.getParameter("cenManagement"));
		inspectionscene.setMissionId(Integer.valueOf(Integer.parseInt(request.getParameter("missionId"))));
	
		inspectionsceneMapper.insert(inspectionscene);
		int newDataId = inspectionscene.getId();//插入操作完成后，mybatis会将新数据的id返回给Inspectionscene实体类，直接getId获取即可
		if (newDataId != 0) {
//			工单插入成功，则将新插入的工单的supMaterial值改为当前工单id
			inspectionscene.setSupMaterial(String.valueOf(newDataId));
//			修改完成后，开始上传支撑材料
			inspectionsceneMapper.update(inspectionscene);
			FileUploadController fUp = new FileUploadController();
			try {
				if (fUp.uploadXcxcFile(request, inspectionscene.getSupMaterial())) {
					return 1;
				} else {
					return 0;
				}
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}
	
	@Override
	public int update(Inspectionscene inspectionscene) {
		return inspectionsceneMapper.update(inspectionscene);
	}

	@Override
	public List<Map<String, Object>> countByDomain() {
		return inspectionsceneMapper.countByDomain();
	}
	
}
